package com.example.springstudy.entity;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
public class SysUserDetails implements UserDetails {

    private Long userId;
    private String username;
    private String password;
    private Integer deptId;
    private Collection<SimpleGrantedAuthority> authorities;
    private Set<String> perms;
    private Boolean isEnabled;
    private int dataScope;

    private User user;

    public SysUserDetails(User user) {
        this.user = user;
        Set<String> roles = user.getRoles();
        if (CollectionUtil.isNotEmpty(roles)) {
            authorities = roles.stream()
                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role)) // 标识角色
                    .collect(Collectors.toSet());
        } else {
            authorities = Collections.EMPTY_SET;
        }
        this.perms = user.getPerms();
        this.dataScope = user.getDataScope();
        this.userId = user.getId();
        this.deptId = user.getDeptId();
        this.username = user.getName();
        this.password = user.getPassword();
        this.isEnabled = user.getIsDeleted() == 0;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.isEnabled;
    }
}
